<?php

namespace App\Http\Middleware;

use App\Models\UserInfo;
use Closure;
use Illuminate\Http\Request;

/**
 * 验证前台绑定读者证和微信授权接口权限
 */
class CheckBindReaderToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // $request->user_info = ['id'=>1,'account_id'=>'','wechat_id'=>''];
        // $request->manage_id = 1;
        // return $next($request);
        
        $token = $this->getToken($request);

        if(empty($token)){
            return  response()->json(['code'=> 204,'msg' => 'token无效']);
        }

        //验证token有效期
        $user_info = UserInfo::select('id' , 'account_id' , 'wechat_id')->where('token' , $token)->first();
        if(empty($user_info)){
            return  response()->json(['code'=> 204,'msg' => 'token无效']);
        }

        if(empty($user_info['account_id'])){
            return  response()->json(['code'=> 206,'msg' => '未绑定读者证，请先绑定读者证']);
        }
      
        $user_info = $user_info->toArray();
        $request->user_info = $user_info;


        return $next($request);
    }

    /**
     * 获取请求参数中的 token 
     * @param request  object 请求参数对象
     */
    public function getToken($request){
        // $token = str_replace('Bearer ', '', $request->header('authorization'));

        // if (!$token) {
        //     $token = $request->token;
        // }   

     //   $token = str_replace('Bearer ', '', $request->header('authorization'));//只能从header头获取
        
        $token = $request->token;
        return $token;
    }


}
